package com.seres.redis;

import com.alibaba.fastjson.JSON;
import com.seres.constant.CacheTimes;
import com.seres.listener.event.RedisDelEvent;
import com.seres.util.StringUtils;
import com.seres.util.ThreadPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description : redis缓存客户端
 * @ClassName : RedisCache
 * @Author : 程磊
 * @Date: 2020-06-22 17:20
 */
@Component
public class RedisCache {

    @Autowired
    ApplicationEventPublisher publisher;

    @Autowired
    private JedisCluster jedisCluster;

    @Autowired
    ThreadPool threadPool;

    public JedisCluster getJedis() {
        return jedisCluster;
    }

    public void del(String key) {
        publisher.publishEvent(new RedisDelEvent(this, key));
    }

    public <T> T getObject(String key, Class<T> cls) {
        String val = this.jedisCluster.get(key);
        if (StringUtils.isNotBlank(val)) {
            return JSON.parseObject(val, cls);
        }
        return null;
    }

    public <T> List<T> getList(String key, Class<T> cls) {
        String val = this.jedisCluster.get(key);
        List<T> res = new ArrayList<T>();
        if (StringUtils.isNotBlank(val)) {
            res = JSON.parseArray(val, cls);
        }
        return res;
    }

    public void cacheOneDay(String val, String key) {
        threadPool.execute(() -> {
            this.jedisCluster.setex(key, CacheTimes.DEFAULT_ONE_DAY, val);
        });
    }

    public void cacheOneWeek(String val, String key) {
        threadPool.execute(() -> {
            this.jedisCluster.setex(key, CacheTimes.DEFAULT_ONE_WEEK, val);
        });
    }


}
